package diy

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/driver/desktop"
	"fyne.io/fyne/v2/widget"
)

type MyIcon struct {
	*widget.Icon
	ShowWinFunc      func() *widget.PopUp
	ShowWin          *widget.PopUp            // 显示的win
	GetLabelTextFunc func() string            // 获取label的text
	PopShow          *widget.PopUpMenu        // 悬浮显示label具体信息
	ClickFunc        func(e *fyne.PointEvent) // 点击事件
}

func NewIcon(res fyne.Resource) *MyIcon {
	s := &MyIcon{
		Icon: widget.NewIcon(res),
	}
	s.ExtendBaseWidget(s)
	s.Icon.SetResource(res)

	return s
}

func (s *MyIcon) SetShowWinFunc(f func() *widget.PopUp) *MyIcon {
	s.ShowWinFunc = f
	return s
}

func (s *MyIcon) SetShowWin(win *widget.PopUp) *MyIcon {
	s.ShowWin = win
	return s
}

func (s *MyIcon) SetLabelTextFunc(f func() string) *MyIcon {
	s.GetLabelTextFunc = f
	return s
}

func (s *MyIcon) SetClickFunc(f func(e *fyne.PointEvent)) *MyIcon {
	s.ClickFunc = f
	return s
}

// Tapped 点击事件
func (b *MyIcon) Tapped(e *fyne.PointEvent) {
	if b.ClickFunc != nil {
		b.ClickFunc(e)
	}
}

// MouseIn 鼠标移入
func (s *MyIcon) MouseIn(event *desktop.MouseEvent) {
	if s.GetLabelTextFunc != nil {
		s.PopShow = widget.NewPopUpMenu(
			fyne.NewMenu("", fyne.NewMenuItem(s.GetLabelTextFunc(), func() {})),
			fyne.CurrentApp().Driver().CanvasForObject(s),
		)

		s.PopShow.ShowAtPosition(
			fyne.CurrentApp().Driver().AbsolutePositionForObject(s).
				Add(
					fyne.NewPos(0, s.Size().Height-35),
				),
		)
		s.PopShow.Resize(fyne.NewSize(s.Size().Width, s.PopShow.MinSize().Height))
	}

	if s.ShowWinFunc != nil {
		s.ShowWin = s.ShowWinFunc()
		s.ShowWinFunc = nil
	}
	if s.ShowWin != nil {
		s.ShowWin.Show()
	}

}

// MouseOut 鼠标移出
func (s *MyIcon) MouseOut() {
	if s.PopShow != nil {
		s.PopShow.Hide()
		s.PopShow = nil
	}

	//if s.ShowWin != nil {
	//	s.ShowWin.Hide()
	//}

}

func (s *MyIcon) MouseMoved(*desktop.MouseEvent) {
}
